class User < ActiveRecord::Base
  self.table_name = "client_users"
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable,
         :validatable,:openid_authenticatable
  # attr_accessor :email, :username, :identity_url
  def self.openid_required_fields
    ["email","roles","oauthtoken","user_id"]
  end
  

  def self.openid_optional_fields
    ["fullname","nickname","gender"]
  end

  def self.build_from_identity_url(identity_url)
    self.create!(:email=>"gust@hy.com",:password=>"11111111",:identity_url => identity_url)
  end

  def openid_fields=(fields)
    fields.each do |key, value|
    # Some AX providers can return multiple values per key
      if value.is_a? Array
      value = value.first
      end
      case key.to_s
      when "fullname"
        self.update_attributes({:username => value}) unless self.username.to_s  == value
        # self.username = value
      when "nickname"
        # self.nickname
      when "email"
         self.update_attributes({:email => value}) unless self.email.to_s  == value
        # self.email = value
      when "gender"
        self.gender = value
      when "user_id"
        self.update_attributes({:server_user_id => value}) unless self.server_user_id.to_s  == value
      when "oauthtoken"
        self.update_attributes({:authentication_token => value}) unless self.authentication_token.to_s  == value
      else
      logger.error "Unknown OpenID field: #{key}"
      end
    end
  end

end
